package _01_sort;

import org.junit.Test;

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

import static _01_sort.SortUtil.swap;

/**
 * @author: mornd
 * @dateTime: 2023/6/23 - 8:36
 * 最优排序算法，双边快排优化，解决数组重复元素过多 + 随机数找基准点 + 低于阈值换成插入排序
 */
public class QuickSortHoarePlus {
//    private static final int INSERTION_SORT_THRESHOLD = 48;
    private static final int INSERTION_SORT_THRESHOLD = 0;

    @Test
    public void test() {
        int[] arr = {4, 3, 1, 7, 6, 9, 11};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    public void quickSort(int[] arr, int left, int right) {
        if (right - left <= INSERTION_SORT_THRESHOLD) {
            insertionSort(arr);
            return;
        }
        if (left < right) {
            int pivotIndex = partition(arr, left, right);
            quickSort(arr, left, pivotIndex - 1);
            quickSort(arr, pivotIndex + 1, right);
        }
    }

    private int partition(int[] arr, int left, int right) {
        // 使用随机数作做基准点
        int randomIndex = left + ThreadLocalRandom.current().nextInt(right - left + 1);
        swap(arr, randomIndex, left);
        int pivot = arr[left];
        int i = left + 1;
        int j = right;
        while (true) {
            while (i <= j && arr[i] < pivot) {
                // i从左向右找大的
                i++;
            }
            while (i <= j && arr[j] > pivot) {
                // j从右向左找小的
                j--;
            }
            if (i >= j) {
                break;
            }
            swap(arr, i, j);
        }
        swap(arr, left, j);
        return j;
    }

    private void insertionSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int t = arr[i];
            int j = i - 1;
            for (; j >= 0 && arr[j] > t; j--) {
                arr[j + 1] = arr[j];
            }
            if (j != i - 1) {
                arr[j + 1] = t;
            }
        }
    }
}
